package com.blb.demo2;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 客户端程序
 */
public class ChatClient {

    public static final int THREADS = 2;

    public void connect(String ip,int port){
        //创建自定义线程池
        int cpus = Runtime.getRuntime().availableProcessors();
        ExecutorService executorService = new ThreadPoolExecutor(
                cpus * THREADS,
                cpus * THREADS,0, TimeUnit.SECONDS,
                new LinkedBlockingQueue<Runnable>());
        try {
            //创建Socket对象
            Socket socket = new Socket(ip,port);
            //获得输入流和输出流，启动两个线程分别完成读和写
            executorService.execute(new WriteRunnable(new ObjectOutputStream(socket.getOutputStream())));
            executorService.execute(new ReadRunnable(new ObjectInputStream(socket.getInputStream())));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        new ChatClient().connect("192.168.1.100",8888);
    }
}
